<?php

require_once 'Vega/Router/Abstract.php';

class Vega_Router_Rewrite extends Vega_Router_Abstract
{
    protected $_routesFile = '';

    protected $_routes = array();

    

    protected $_enableUrlMap = true;

    public function __construct($file = 'routes')
    {
        $this->setRoutesFile($file);
    }

    public function enableUrlMap($enable = true)
    {
        $this->_enableUrlMap = $enable;
    }

    public function setRoutesFile($file)
    {
        $this->_routesFile = $file;
        return $this;
    }

    public function getRoutesFile()
    {
        return $this->_routesFile;
    }

    

    public function route()
    {
        $info = false;

        if ($this->_enableUrlMap)
        {
            try
            {
                $this->_routes = Vega_App::getInstance()->loadConfig($this->_routesFile);
            }
            catch (Vega_Exception $e)
            {
                
                // do nothing
            }
            
            
            if (count($this->_routes) > 0)
            {
                if (isset($this->_routes['domain']))
                {
                    $info = $this->_routeDomain();

                    // if the info is directly set. return the request object
                    if (is_array($info))
                    {
                        return $this->_makeRequestObject($info);
                    }
                }

                $urlInfo = $this->_routeUrl($info, $this->_routes['url']['first']);

                if (is_array($urlInfo))
                {
                    return $this->_makeRequestObject($urlInfo);
                }
                $info = (is_string($info) ? $info : $this->getRequestUrl());

                $urlInfo = $this->_parseDefaultRoute($info);
                
                if (is_array($urlInfo))
                {
                    return $this->_makeRequestObject($urlInfo);
                }
                
                $urlInfo = $this->_routeUrl($info, $this->_routes['url']['second']);
                
                if (is_array($urlInfo))
                {
                    return $this->_makeRequestObject($urlInfo);
                }
                return false;
            }
        }

        $info = (is_string($info) ? $info : $this->getRequestUrl());

        $info = $this->_parseDefaultRoute($info);
        
        return $this->_makeRequestObject($info);
    }

    protected function _parseDefaultRoute($info)
    {
        
        $return = array('params' => array(), 'module' => 'index', 'action' => 'index');
        
        if (strlen($info) == 0 || $info == '/')
        {
            return $return;
        }
        
        $parts = explode('/', substr($info, 1));
        $count = count($parts);

        for ($i = 0; $i < $count; $i++)
        {
            if (empty($parts[$i]))
            {
                continue;
            }
            
            if ($i > 1)
            {
                $return['params'][] = $parts[$i];
            }
            elseif ($i == 1)
            {
                $return['action'] = $parts[1];
            }
            else
            {
                $return['module'] = $parts[0];
            }
        }
        
        if (!$this->_checkModuleExistent($return['module'], $return['action']))
        {
            return false;
        }

        return $return;
    }
    
    protected function _routeDomain()
    {
        foreach ($this->_routes['domain'] as $domain => $info)
        {
            if (preg_match_all('~' . $domain . '~', $_REQUEST['HTTP_HOST'], $matches))
            {
                
                if (is_string($info))
                {
                    return $info;
                }
                $matches = $this->_getUrlMatches($matches);
                $info['params'] = array();
                $info['url_matches'] = $matches;
                return $info;
            }
        }
        return false;
    }

    protected function _routeUrl($requestUrl = false, $routes)
    {
        if (false === $requestUrl)
        {
            $requestUrl = $this->getRequestUrl();
        }
        
        foreach ($routes as $url => $info)
        {
           
            if (preg_match_all('~' . $url . '~', $requestUrl, $matches))
            {
                $info['params'] = array();
                
                $temp = $matches[0][0];

                $temp = substr($requestUrl, strlen($temp));
                
                if (strlen($temp) > 0)
                {
                    
                    /*if ($temp[0] == '/')
                    {
                        $temp = substr($temp, 1);
                    }*/

                    $temp = explode('/', $temp);

                    /*if (!isset($info['action']))
                    {
                        $first = array_shift($temp);
                        $info['action'] = (!empty($first) ? $first : 'index');
                    }*/
                    
                    if (count($temp) > 0)
                    {
                        
                        
                         foreach ($temp as $param)
                        {
                            $info['params'][] = $param;
                        }
                    }
                }
                
                if (!isset($info['action']))
                {
                    if (isset($info['params']))
                    {
                        $info['action'] = array_shift($info['params']);
                    }
                    else
                    {
                        $info['action'] = 'index';
                    }
                }
                
                if (!$this->_checkModuleExistent($info['module'], $info['action']))
                {
                    
                    return false;
                }
                
                $urlmatches = $this->_getUrlMatches($matches);
                $info['url_matches'] = $urlmatches;
                return ($info);
            }
        }
        return false;
    }

    protected function _getUrlMatches($matches)
    {
        $urlmatches = array();

        foreach ($matches as $count => $match)
        {
            if ($count == 0)
            {
                continue;
            }

            $urlmatches[] = $match[0];
        }
        return $urlmatches;
    }

    protected function _makeRequestObject($info)
    {
        require_once 'Vega/Request.php';

        $info['request_url'] = $this->getRequestUrl();

        return new Vega_Request($info);
    }
    
    protected function _checkModuleExistent($module, $action)
    {
        return Vega_App::getInstance()->checkModuleExistent($module, $action);
    }
}
